﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lacrima.Framework.Persistence
{
    public abstract class DbAdapter : IDbAdapter
    {
        public virtual IDbAdapter GetInstance()
        {
            return this;
        }

        public virtual IDbConnection GetDbConnection(string connectionString)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException("数据库连接字符串为空，请检查数据库配置信息");
            }
            else
            {
                return new OleDbConnection(connectionString);
            }
        }

        public virtual IDbCommand GetDbCommand(IDbConnection dbConnection)
        {
            return dbConnection.CreateCommand();
        }

        public virtual IDbTransaction GetDbTransaction(IDbConnection dbConnection)
        {
            return dbConnection.BeginTransaction();
        }

        public virtual DbDataAdapter GetDbDataAdapter(IDbCommand dbCommand)
        {
            return new OleDbDataAdapter(dbCommand as OleDbCommand);
        }

        public virtual void Dispose(IDbConnection dbConnection)
        {
            try
            {
                if (null != dbConnection)
                {
                    dbConnection.Close();
                    dbConnection.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dbConnection = null;
            }
        }

        public virtual void Dispose(IDbCommand dbCommand)
        {
            try
            {
                if (null != dbCommand)
                {
                    dbCommand.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dbCommand = null;
            }
        }

        public virtual void Dispose(IDbTransaction dbTransaction)
        {
            try
            {
                if (null != dbTransaction)
                {
                    dbTransaction.Dispose();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                dbTransaction = null;
            }
        }
    }
}
